//
//  LSZPasswordLoginVC.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/8/13.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZPasswordLoginVC.h"
#import "JPUSHService.h"
@interface LSZPasswordLoginVC ()<UITextFieldDelegate>
@property(nonatomic,strong) UITextField * textFieldPassword;
@property(nonatomic,strong) UITextField * textFieldPhone;
@property(nonatomic,strong) UIButton    * butChooseState;

@property(nonatomic,strong) UIView      * viewPhone;
@property(nonatomic,strong) UIView      * viewPassword;
@property(nonatomic,strong) TPKeyboardAvoidingScrollView * backScrollView;
@property(nonatomic,strong) UILabel     * labelPassword;
@end

@implementation LSZPasswordLoginVC
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"密码登录";
    TPKeyboardAvoidingScrollView * backScrollView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth,ScreenHeight)];
    backScrollView.userInteractionEnabled = YES;
    [self.view addSubview: backScrollView];
 
    UIImageView  * imageViewBack = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    imageViewBack.image = [UIImage imageNamed:@"登录背景"];
    imageViewBack.userInteractionEnabled = YES;
    [backScrollView addSubview:imageViewBack];
    
    UILabel * labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT-20, ScreenWidth, 35)];
    labelTitle.text =@"新郑扶贫";
    labelTitle.textColor = RGBColor(196, 23, 0);
    labelTitle.textAlignment = NSTextAlignmentCenter;
    [labelTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:35]];
    [imageViewBack addSubview:labelTitle];
    
    UIImageView * imageViewTop = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-WidthScal750(160))/2, CGRectGetMaxY(labelTitle.frame)+30, WidthScal750(160), WidthScal750(165.6))];
    imageViewTop.image = [UIImage imageNamed:@"login_top"];
    [imageViewBack addSubview:imageViewTop];
    
//    UIView * viewContent = [[UIView alloc]init];
//    viewContent.backgroundColor = [UIColor whiteColor];
//    viewContent.frame = CGRectMake(10, CGRectGetMaxY(imageViewTop.frame)+50, ScreenWidth-20, 120);
//    [viewContent.layer setBorderWidth:1.0f];
//    [viewContent.layer setBorderColor:dividerColor.CGColor];
//    [imageViewBack addSubview:viewContent];
//
//    UIView * underLinePasView = [[UIView alloc]initWithFrame:CGRectMake(1, (viewContent.frame.size.height-1)/2, viewContent.frame.size.width-2, 1)];
//    underLinePasView.backgroundColor = dividerColor;
//    [viewContent addSubview:underLinePasView];
//
//    UIImageView * imageViewPhone = [[UIImageView alloc]initWithFrame:CGRectMake(10, 20, 15, 20)];
//    imageViewPhone.backgroundColor = [UIColor yellowColor];
//    [viewContent addSubview:imageViewPhone];
//
//    self.textFieldPhone = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageViewPhone.frame)+20, 10,underLinePasView.frame.size.width - CGRectGetMaxX(imageViewPhone.frame)-20, 40)];
//    self.textFieldPhone.placeholder = @"请输入账号";
//    [viewContent addSubview:self.textFieldPhone];
//
//    UIImageView * imageViewPassword = [[UIImageView alloc]initWithFrame:CGRectMake(10, 20+CGRectGetMaxY(underLinePasView.frame), 15, 20)];
//    imageViewPassword.backgroundColor = [UIColor yellowColor];
//    [viewContent addSubview:imageViewPassword];
//
//    self.textFieldPassword = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageViewPhone.frame)+20, 10+CGRectGetMaxY(underLinePasView.frame),underLinePasView.frame.size.width - CGRectGetMaxX(imageViewPhone.frame)-20, 40)];
//    self.textFieldPassword.placeholder = @"请输入密码";
//    [viewContent addSubview:self.textFieldPassword];
    
  
     UILabel * labelPhone = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(imageViewTop.frame)+40, ScreenWidth-40, 16)];
     labelPhone.textColor = [UIColor redColor];
     labelPhone.font = FONT_(14);
     labelPhone.text = @"手机号";
     labelPhone.textColor = themeColor;
     [imageViewBack addSubview:labelPhone];
     
     self.textFieldPhone = [[UITextField alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(labelPhone.frame)+20, ScreenWidth-40, 20)];
    self.textFieldPhone.tag = 1;
    self.textFieldPhone.delegate = self;
     [imageViewBack addSubview:self.textFieldPhone];
    NSString * lastPhone = NullStringjudgment(NSStr([[NSUserDefaults standardUserDefaults] stringForKey:@"lastPhone"]));
    if ([lastPhone isEqualToString:@""]) {
        self.textFieldPhone.placeholder = @"请输入手机号";
    }else{
        self.textFieldPhone.text = lastPhone;
    }
    
    self.viewPhone = [[UIView alloc]initWithFrame:CGRectMake(0,self.textFieldPhone.frame.size.height+5,self.textFieldPhone.frame.size.width,1)];
    self.viewPhone.backgroundColor = RGBColor(212, 212, 212);//themeColor;
     [self.textFieldPhone addSubview:self.viewPhone];
 
    self.labelPassword = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.textFieldPhone.frame)+15, ScreenWidth-40, 16)];
    self.labelPassword.textColor = [UIColor redColor];
    self.labelPassword.font = FONT_(14);
    self.labelPassword.text = @"密码";
    self.labelPassword.hidden = YES;
    self.labelPassword.textColor = themeColor;
    [imageViewBack addSubview:self.labelPassword];
     
     self.textFieldPassword = [[UITextField alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.labelPassword.frame)+15, ScreenWidth-40-40, 20)];
    self.textFieldPassword.secureTextEntry = YES;
    self.textFieldPassword.tag = 2;
    self.textFieldPassword.delegate = self;
    self.textFieldPassword.placeholder = @"密码";
    [imageViewBack addSubview:self.textFieldPassword];
     
     self.butChooseState = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.textFieldPassword.frame)+10, CGRectGetMaxY(self.textFieldPhone.frame)+20, 30, 30)];
     [self.butChooseState setImage:[UIImage imageNamed:@"登录_保密"] forState:UIControlStateNormal];
     [self.butChooseState addTarget:self action:@selector(clickChooseState:) forControlEvents:UIControlEventTouchUpInside];
     [imageViewBack addSubview:self.butChooseState];
     self.viewPassword = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.textFieldPassword.frame),CGRectGetMaxY(self.textFieldPassword.frame)+10,self.viewPhone.frame.size.width,1)];
     self.viewPassword.backgroundColor = RGBColor(212, 212, 212);
     [imageViewBack addSubview:self.viewPassword];
 
    UIButton * but = [[UIButton alloc]init];
    but.frame = CGRectMake(20, CGRectGetMaxY(self.viewPassword.frame)+50, ScreenWidth-40, 50);
    but.backgroundColor = themeColor;
    [but setTitle:@"登录" forState:UIControlStateNormal];
    [but.layer setMasksToBounds:YES];
    [but.layer setCornerRadius:4];
    [but setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [but addTarget:self action:@selector(clickPassword) forControlEvents:UIControlEventTouchUpInside];
    [imageViewBack addSubview:but];
    UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAction)];
    [self.view addGestureRecognizer:click];
}
#pragma mark - 添加手势
-(void)clickAction
{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.viewPhone.backgroundColor = RGBColor(212, 212, 212);
        self.viewPassword.backgroundColor = RGBColor(212, 212, 212);
    } completion:nil];
}
-(void)clickChooseState:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected == YES) {
        NSLog(@"111111");//明文
        self.textFieldPassword.secureTextEntry = NO;
        [self.butChooseState setImage:[UIImage imageNamed:@"登录_不保密"] forState:UIControlStateNormal];
    }else{
        NSLog(@"222222");
        self.textFieldPassword.secureTextEntry = YES;
        [self.butChooseState setImage:[UIImage imageNamed:@"登录_保密"] forState:UIControlStateNormal];
    }
}
//开始编辑时触发
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        if (textField.tag == 1) {
            self.viewPhone.backgroundColor = themeColor;
            self.viewPassword.backgroundColor = RGBColor(212, 212, 212);
        }
        if (textField.tag == 2) {
            self.labelPassword.hidden = NO;
            self.viewPhone.backgroundColor = RGBColor(212, 212, 212);
            self.viewPassword.backgroundColor = themeColor;
        }
    } completion:nil];
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString * str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField.tag == 2) {
        if (str.length > 0) {
            self.labelPassword.hidden = NO;
        }else{
            self.labelPassword.hidden = YES;
        }
    }
    return YES;
}
-(void)clickPassword
{
    //打包用这个
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:self.textFieldPhone.text,@"username",self.textFieldPassword.text,@"password", nil];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:NSStr(self.textFieldPhone.text) forKey:@"lastPhone"];
        [userDefaults synchronize];
    
    
//    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"12345",@"username",@"111111",@"password", nil];//县级扶贫用户
    
    //    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"18538602302",@"username",@"123456",@"password", nil];//县级扶贫用户
    //    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"18538602302",@"username",@"123456",@"password", nil];//乡镇扶贫用户
    //    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"18538602302",@"username",@"123456",@"password", nil];//帮扶责任人
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString * url = [NSString stringWithFormat:@"%@%@",URLTotal,@"/login"];
    NSString * encodingString = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:encodingString parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:jsonObject[@"token"] forKey:@"token"];
        [defaults synchronize];
        [InterfaceJumpEncapsulation jumpToNewTabBar:0];
        [self login];
        if ([[jsonObject allKeys] containsObject:@"id"]) {
//            [JPUSHService setTags:nil alias:jsonObject[@"name"] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
            [JPUSHService setAlias:[NSString stringWithFormat:@"%@",jsonObject[@"id"]] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                NSLog(@"rescode: %ld, \ntags: %@, \nalias: %@\n", (long)iResCode, @"tag" , iAlias);
            } seq:0];
        }
        //        [LSZRequestData getMyOrganization:^(BOOL isOk, NSString * str, NSDictionary * dic) {
        //            if (isOk == YES) {
        //                [InterfaceJumpEncapsulation jumpToNewTabBar:0];
        //                [self login];
        //            }
        //        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@", error);
        NSString * str = [self ErrorMessageProcessing:error];
        AlertKuangView * alert = [AlertKuangView new];
        [alert moveJingGaoKuang:str :self.view];
    }];
}
-(void)login
{
    [InterfaceJumpEncapsulation jumpToNewTabBar:0];
}

-(NSString *)ErrorMessageProcessing:(NSError *)error
{
    NSString * str = [NSString stringWithFormat:@"%@",error.userInfo[@"NSLocalizedDescription"]];
    NSArray *array = [str componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
    NSInteger count = array.count -1;
    NSString * strContent = array[count];
    NSLog(@"%@",strContent);
    strContent = [strContent stringByReplacingOccurrencesOfString:@"(" withString:@""];
    strContent = [strContent stringByReplacingOccurrencesOfString:@")"withString:@""];
    NSString * string = [[NSString alloc]init];
    if ([strContent isEqualToString:@"403"]) {
        string = @"重复登录";
    }else if ( [strContent isEqualToString:@"400"]){
        string = @"参数返回错误";
    }else if ([strContent isEqualToString:@"401"] ){
        string = @"账号或密码错误";
    }else if ( [strContent isEqualToString:@"404"]){
        string = @"路径错误";
    }else if ( [strContent isEqualToString:@"500"]){
        string = @"未知错误";
    }else{
        string = strContent;
    }
    return string;
}
@end
